package com.littlerpc.protocol.net.netty.client;

import com.littlerpc.protocol.net.common.*;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 *
 * @author ChengPeng
 * @date 2017/6/13
 */
public class NettyClientHander extends SimpleChannelInboundHandler<RpcResponse> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
//        ctx.writeAndFlush(new RpcRequest());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcResponse msg) throws Exception {
        //获取结果，并将结果放入future中
        RpcFuture<RpcResponse> future = RpcFuturePool.getFuture(msg.getRequestId());

        if(msg.isError()) {
            msg.getError().printStackTrace();
        }

        future.setResult(msg);
        future.done();
        if(future.getListeners().size() > 0) {
            future.getListeners().forEach(l -> l.doSomething());
        }


    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        super.exceptionCaught(ctx, cause);
    }
}
